package com.imy.luascript.config;

import android.content.Context;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.module.AppGlideModule;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

@GlideModule
public class GlideModuleConfig extends AppGlideModule {
  @Override
  public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
    //builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
    //配置内存缓存大小 1MB
    builder.setMemoryCache(new LruResourceCache(1024 * 1024));
    //配置图片池大小   1MB
    builder.setBitmapPool(new LruBitmapPool( 1024 * 1024));
    //设置磁盘缓存大小
    int size = 100 * 1024 * 1024;
    //设置磁盘缓存
    builder.setDiskCache(new InternalCacheDiskCacheFactory(context, size));
  }

  @Override
  public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
    super.registerComponents(context, glide, registry);
    //
    ////添加拦截器到Glide
    //OkHttpClient.Builder builder = new OkHttpClient.Builder();
    //builder.addInterceptor(new ErrorInterceptor());
    //OkHttpClient okHttpClient = builder.build();
    //
    ////原来的是  new OkHttpUrlLoader.Factory()；
    //registry.replace(GlideUrl.class, InputStream.class, new HttpGlideUrlLoader.Factory(okHttpClient));
  }
  private static class ErrorInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Response response = chain.proceed(request);
      return response;
    }
  }
}
